通过tree树形控件的default-checked-keys属性来设置默认选中的节点

html.vue

<el-form-item label="角色权限:">
    <el-tree :data="data2" 
        show-checkbox 
        node-key="id" 
        @check="handleNodeClick" 
        :default-expanded-keys="[]" 
        ref="tree" 
        :default-checked-keys="default_select" 
        :props="defaultProps">
    </el-tree>
</el-form-item>

html.js

data() {
        return {
            data2: [],
            defaultProps: {
                children: 'child',
                label: 'name'
            },
            menu_ids: [],
            // 默认选中
            default_select: [],
            role_id: 0,
        }
    },
    methods: {
        /**
         * 获取详情
         */
        getDetail() {
            let that = this;
            that.$http.post(that.adminApi.api_url + "/Role/show_edit", {
                token: that.token,
                role_id: that.role_id
            }, {
                emulateJSON: true
            }).then(
                function (res) {
                    var data = res.body;
                    if (data) {
                        that.ruleForm.name = data.name;
                        that.ruleForm.sort = data.sort;
                        that.ruleForm.status = data.status.toString();
                        
                        
                        /**重点开始*/
                        if(typeof (data.menu_id) == 'object'){
                            //转数组
                            data.menu_id = Object.keys(data.menu_id).map(key=> data.menu_id[key]);
                        }
                        //赋值
                        data.menu_id.forEach((value)=>{
                            that.default_select.push(value);
                        });

                        setTimeout(function () {
                            that.default_select.forEach((value)=>{
                                that.$refs.tree.setChecked(value,true,false)
                            });
                        },100);
                        that.menu_ids = data.menu_id;
                        /**重点结束*/
                    }
                });
        },

        /**
         * 属性控件
         */
        handleNodeClick(e, data) {
            console.log(data);
            console.log(e);
            this.menu_ids = data.checkedKeys
        },
    }

总结,Tree树形控件通过后台接口获取到数组数据,还需要再次遍历,将它再遍历为数组,这样我们才可以调用,如果直接从后台获取到数组来调用的时候,我们是获取不到这个数组中的内容。


MRZYD
145 声望10 粉丝

一个初学的小菜鸟,望各位大佬多多指教